package goplatform

import (
	"errors"
	"fmt"
	"log"
	"reflect"
)

func init() {
	ff, _ := GetFieldFactory()

	var fs = FieldString{
		Name:     "string",
		Elements: FieldStringElement{}}
	if err := ff.RegisterFieldType(&fs); err != nil {
		log.Println("FieldString RegisterFieldType Fail")
	} else {
		//fString, _ := ff.GetFieldType("string")
		log.Println("FieldString RegisterFieldType Success")
	}
}

type FieldStringElement struct {
	Size      int    `orm:"size:255" json:"size"`
	Default   string `orm:"default:''" json:"default"`
	MatchType string `orm:"" json:"match_type"`
}

type FieldString struct {
	Name     string
	GormTag  string
	Elements FieldStringElement
	Errs     []error
}

//func (f *FieldConfig) RegisterFieldString(pModel PModel, name string) (*FieldString, error) {
//	fs := FieldConfig{}
//	return &fs, nil
//}

func (f *FieldString) GetName() string {
	return f.Name
}

func (f *FieldString) GetStruct() interface{} {
	return f
}

//func (f *FieldString) GetElement(name string)  {
//	//fmt.Printf("%+v", name)
//	return f.Elements
//}

func (f *FieldString) CodeOrmStates() []string {
	defer func() {
		if r := recover(); r != nil {
			log.Println("\n-Recovered!-----------\nRecovered in CodeOrmStates", r)
			f.Errs = append(f.Errs, errors.New("FieldString CodeOrmStates recover! "))
		}
	}()
	//fmt.Printf("FieldString=>%+v\n", f)

	t := reflect.TypeOf(&f.Elements).Elem()
	var ormElementMap []string
	var (
		oSize      = t.Field(0).Tag.Get(fieldFactory.OrmTagName)
		oDefault   = t.Field(1).Tag.Get(fieldFactory.OrmTagName)
		oMatchType = t.Field(2).Tag.Get(fieldFactory.OrmTagName)
	)
	if f.Elements.Size != 0 {
		oSize = "size:" + fmt.Sprintf("%d", f.Elements.Size)
		ormElementMap = append(ormElementMap, oSize)
	} else {
		ormElementMap = append(ormElementMap, oSize)
	}
	if f.Elements.Default != "" {
		oDefault = fmt.Sprintf("default:'%s'", f.Elements.Default)
		ormElementMap = append(ormElementMap, oDefault)
	} else {
		ormElementMap = append(ormElementMap, oDefault)
	}
	if oMatchType != "" {
		ormElementMap = append(ormElementMap, oMatchType)
	}
	// User
	//if f.GormTag != "" {
	//	ormElementMap = append(ormElementMap, f.GormTag)
	//}
	//return fmt.Sprintf("gorm:\"%s\"", strings.Join(ormElementMap, ";"))
	return ormElementMap
}

func (f *FieldString) EventUpdate() string {
	return "!!!!!FieldInt.EventUpdate"
}
